package com.logistics.account.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logistics.account.entity.domain.AccountRole;
import com.logistics.account.entity.model.AccountRoleSave;
import com.logistics.account.mapper.AccountRoleMapper;
import com.logistics.utils.constants.Message;
import com.logistics.utils.exception.MessageException;
import com.logistics.utils.message.Manager;
import com.logistics.utils.tool.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AccountRoleService extends ServiceImpl<AccountRoleMapper, AccountRole> {

    /**
     * 根据用户Id查找角色ID
     * @param userId
     * @return
     */
    public List<String> roleIdsByUserId(String userId) throws MessageException {
        if(StringUtils.isNull(userId)){
            throw new MessageException(Manager.getMessage(Message.MSG1004.getCode()));
        }
        List<AccountRole> list = this.list(new
                LambdaQueryWrapper<AccountRole>().eq(AccountRole::getAccountId, Integer.parseInt(userId)));
        return list.stream().map(e -> e.getRoleId().toString()).collect(Collectors.toList());
    }

    /**
     * 检查角色ID是否能删除
     * @param ids
     * @throws MessageException
     */
    public void checkRoleId(String ids) throws MessageException {
        List<AccountRole> list = this.list(new LambdaQueryWrapper<AccountRole>().
                in(AccountRole::getRoleId, StringUtils.splitToList(ids, ",")));
        if(list.size() > 0){
            throw new MessageException(Manager.getMessage(Message.MSG1008.getCode()));
        }
    }

    /**
     * 保存
     * @param list
     */
    public void save(List<AccountRoleSave> list){
        this.saveBatch(list.stream().map(e -> AccountRole.build(e)).collect(Collectors.toList()));
    }

    /**
     * 删除
     * @param ids
     */
    public void delete(String ids){
        this.remove(new LambdaQueryWrapper<AccountRole>().in(AccountRole::getAccountId,
                StringUtils.splitToList(ids, ",")));
    }
}
